package com.example.administrator.x2picturetransliteration.Util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;

/**
 * 媒体库新增删除
 * Created by Administrator on 2019/9/25.
 */

public class MediaUtil {

    /**
     * 添加
     * */
    public static void MediaScanner(Context context, File file)
    {
        MediaScannerConnection.scanFile(context ,
                new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
    }

    //删除文件后更新数据库  通知媒体库更新文件夹
    public static void updateFileFromDatabase(Context context,File file){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String[] paths = new String[]{Environment.getExternalStorageDirectory().toString()};
            MediaScannerConnection.scanFile(context, paths, null, null);
            MediaScannerConnection.scanFile(context, new String[] {
                            file.getAbsolutePath()},
                    null, new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri)
                        {
                        }
                    });
        } else {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

    public static void DeleteMusicDatabase(Context context,long ID,hd mhd){    //这里的ID是数据库中获取的文件_Id
        ContentResolver contentResolver = context.getContentResolver();
        Uri deleteIdUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, ID);
        //将id和路径绑定在一起，此Id相当于数据库中的主键
        int res = contentResolver.delete(deleteIdUri, null, null);
        //传入绑定后的路径后，后续两个参数null的意思是删除对应路径下的所有数据库记录，因为我们绑定了
        //唯一的Id，所以能够成功删除文件，但是如果绑定失败，可能会出现类似增一个表被删除的情况。
        //delete的返回值是该操作所影响的行数，所以当res = 1,就是删除了一条记录，0 表示删除失败

        if (res==1){

            mhd.hdff();
            new ToastUtil(context).getToast(false,"删除成功").show();

        }else {

            new ToastUtil(context).getToast(false,"删除失败").show();
        }

    }

    public interface hd{

        void hdff();
    }

}
